package com.open.capacity.reimburse.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.open.capacity.model.system.SysUser;
import com.open.capacity.reimburse.dto.CarApplyHistoryDto;
import com.open.capacity.reimburse.excel.CarExcelModel;
import com.open.capacity.reimburse.util.uuid.UUIDUtils;
import com.open.capacity.user.model.SysCompany;
import com.open.capacity.user.model.SysDepartment;
import com.open.capacity.user.service.SysCompanyService;
import com.open.capacity.user.service.SysDepartmentService;
import com.open.capacity.user.service.SysUserService;
import com.open.capacity.utils.StringUtil;
import com.open.capacity.utils.SysUserUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.open.capacity.commons.PageResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.open.capacity.commons.CodeEnum;

import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.MapUtils;

import com.open.capacity.reimburse.entity.BaseCar;
import com.open.capacity.reimburse.dao.BaseCarDao;
import com.open.capacity.reimburse.service.BaseCarService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@Service
public class BaseCarServiceImpl implements BaseCarService {

    @Autowired
    private BaseCarDao baseCarDao;

    @Autowired
    private SysCompanyService companyService;

    @Autowired
    private SysDepartmentService departmentService;

    @Autowired
    private SysUserService userService;

    /**
     * 添加
     *
     * @param baseCar
     */
    public int save(BaseCar baseCar) {
        SysUser loginUser = SysUserUtil.getLoginAppUser();
        baseCar.setId(UUIDUtils.getOriginalUUIDWithoutBar());

        BaseCar model = baseCarDao.findByLicensePlateNumber(baseCar.getLicensePlateNumber());
        if (model != null && !model.getId().equals(baseCar.getId())) {
            throw new IllegalArgumentException("车牌号已存在");
        }

        if (StringUtil.isEmpty(baseCar.getCompanyName())) {
            SysCompany company = companyService.findById(baseCar.getCompanyId());
            baseCar.setCompanyName(company == null ? "" : company.getFullName());
        }
        if (StringUtil.isEmpty(baseCar.getDepartmentName())) {
            SysDepartment department = departmentService.findById(baseCar.getDepartmentId());
            baseCar.setDepartmentName(department == null ? "" : department.getFullName());
        }
        if (baseCar.getStatus() == null) {
            baseCar.setStatus(1);
        }
        baseCar.setCreateTime(new Date());
        baseCar.setCreateUserid(loginUser.getId());
        baseCar.setCreateUsername(loginUser.getRealName());
        return baseCarDao.save(baseCar);
    }

    /**
     * 修改
     *
     * @param baseCar
     */
    public int update(BaseCar baseCar) {
        SysUser loginUser = SysUserUtil.getLoginAppUser();

        BaseCar model = baseCarDao.findByLicensePlateNumber(baseCar.getLicensePlateNumber());
        if (model != null && !model.getId().equals(baseCar.getId())) {
            throw new IllegalArgumentException("车牌号已存在");
        }

        if (StringUtil.isNotEmpty(baseCar.getCompanyId())) {
            SysCompany company = companyService.findById(baseCar.getCompanyId());
            baseCar.setCompanyName(company == null ? "" : company.getFullName());
        }
        if (StringUtil.isNotEmpty(baseCar.getDepartmentId())) {
            SysDepartment department = departmentService.findById(baseCar.getDepartmentId());
            baseCar.setDepartmentName(department == null ? "" : department.getFullName());
        }
        baseCar.setUpdateTime(new Date());
        baseCar.setUpdateUserid(loginUser.getId());
        baseCar.setUpdateUsername(loginUser.getRealName());
        return baseCarDao.update(baseCar);
    }

    @Override
    public int updateProcessId(String id, String processId) {
        return baseCarDao.updateProcessId(id, processId);
    }


    /**
     * 删除
     *
     * @param id
     */
    public int delete(String id) {
        return baseCarDao.delete(id);
    }

    /**
     * 查询记录
     *
     * @param id
     * @return
     */
    public BaseCar findById(String id) {
        return baseCarDao.findById(id);
    }

    /**
     * 分页
     *
     * @param params
     * @return
     */
    public PageResult<BaseCar> pageAll(Map<String, Object> params) {
        //设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
        if (MapUtils.getInteger(params, "page") != null && MapUtils.getInteger(params, "limit") != null)
            PageHelper.startPage(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"), true);

        List<BaseCar> list = baseCarDao.findAll(params);
        PageInfo<BaseCar> pageInfo = new PageInfo(list);

        return PageResult.<BaseCar>builder().data(pageInfo.getList()).resp_code(CodeEnum.SUCCESS.getCode()).count(pageInfo.getTotal()).build();
    }

    /**
     * 分页显示车辆使用历史
     *
     * @param params
     * @return
     */
    public PageResult<CarApplyHistoryDto> pageHistory(Map<String, Object> params) {
        //设置分页信息，分别是当前页数和每页显示的总记录数【记住：必须在mapper接口中的方法执行之前设置该分页信息】
        if (MapUtils.getInteger(params, "page") != null && MapUtils.getInteger(params, "limit") != null)
            PageHelper.startPage(MapUtils.getInteger(params, "page"), MapUtils.getInteger(params, "limit"), true);

        List<CarApplyHistoryDto> list = baseCarDao.findHistory(params);
        PageInfo<CarApplyHistoryDto> pageInfo = new PageInfo(list);

        return PageResult.<CarApplyHistoryDto>builder().data(pageInfo.getList()).resp_code(CodeEnum.SUCCESS.getCode()).count(pageInfo.getTotal()).build();
    }

    /**
     * 列表
     *
     * @param params
     * @return
     */
    public List<BaseCar> findAll(Map<String, Object> params) {
        return baseCarDao.findAll(params);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int importExcel(MultipartFile multipartFile) throws Exception {
        ImportParams params = new ImportParams();
        params.setHeadRows(1);
        // params.setTitleRows(0);
        // 开启excel校验
        params.setNeedVerify(true);

        ExcelImportResult<CarExcelModel> result = new ExcelImportResult();
        try {
            result = ExcelImportUtil.importExcelMore(multipartFile.getInputStream(),
                    CarExcelModel.class, params);
        } catch (Exception e) {

            log.error("从文件读取数据错误:{}", e.getMessage());
        }
        if (result.isVerifyFail()) {
            StringBuilder temp = new StringBuilder();
            for (CarExcelModel entity : result.getFailList()) {
                temp.append("第").append(entity.getRowNum()).append("行的错误是：").append(entity.getErrorMsg());
            }
            throw new Exception("Excel文件校验不通过:" + temp.toString());
        }

        SysCompany company;
        SysDepartment department;
        SysUser user;
        for (CarExcelModel item : result.getList()) {
            BaseCar car = new BaseCar();
            if (StringUtil.isNotEmpty(item.getCompanyName())) {
                company = companyService.findByName(item.getCompanyName());
                if (company != null) {
                    item.setCompanyId(company.getId());
                    if (StringUtil.isNotEmpty(item.getDepartmentName())) {
                        department = departmentService.findByName(company.getId(), item.getDepartmentName());
                        if (department != null) {
                            item.setDepartmentId(department.getId());
                            if (StringUtil.isNotEmpty(item.getUserName())) {
                                user = userService.findByName(company.getId(), department.getId(), item.getUserName());
                                item.setUserId(user.getId());
                            }
                            if (StringUtil.isNotEmpty(item.getDriverName())) {
                                user = userService.findByName(company.getId(), department.getId(), item.getDriverName());
                                item.setDriverId(user == null ? "" : user.getId());
                            }
                        }
                    }
                }
            }
            BeanUtils.copyProperties(item, car);
            save(car);
        }
        return result.getList().size();
    }

}
